package com.cloud.redis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@RestController
public class RedisController {
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * getRedisScript 读取脚本工具类
     * 这里设置为Long,是因为ipLimiter.lua 脚本返回的是数字类型
     */
    private DefaultRedisScript<Long> lock;
    private DefaultRedisScript<Long> unlock;

    @PostConstruct
    public void init() {
        lock = new DefaultRedisScript<>();
        lock.setResultType(Long.class);
        lock.setScriptSource(new ResourceScriptSource(new ClassPathResource("lock.lua")));

        unlock = new DefaultRedisScript<>();
        unlock.setResultType(Long.class);
        unlock.setScriptSource(new ResourceScriptSource(new ClassPathResource("unlock.lua")));
    }
    @GetMapping("/lock")
    public Object test(){
        List<String> key=new ArrayList<>();
        key.add("12");
        Object execute = redisTemplate.execute(lock, key, "123", 10);
        return key;
    }
}
